package com.wl.optional;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class OptionalTest {
    private static final Logger logger = LoggerFactory.getLogger(OptionalTest.class);

    @Test
    public void whenCreateOfNullableOptional_thenOk() {
        String name = "John";
        Optional<String> opt = Optional.ofNullable(name);
        System.out.println("name = " + name);
        assertEquals("John", opt.get());
    }

    @Test
    public void whenCheckIfPresent_thenOk() {
        User user = new User("wanglei", 23);
        Optional<User> opt = Optional.ofNullable(user);
        assertTrue(opt.isPresent());
        assertEquals(user.getAge(), opt.get().getAge());
    }

    @Test
    public void whenEmptyValue_thenReturnDefault() {
        User user = null;
        User user2 = new User("wanglei", 23);
        User result = Optional.ofNullable(user).orElse(user2);
        assertEquals(user2.getAge(), result.getAge());
    }

    @Test
    public void givenPresentValue_whenCompare_thenOk() {
        User user = new User("wanglei", 23);
        logger.info("Using orElse");
        User result = Optional.ofNullable(user).orElse(createNewUser());
        logger.info("Using orElseGet");
        User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
    }

    private User createNewUser() {
        logger.debug("Creating New User");
        return new User("duxiaozhu", 23);
    }

    @Test(expected = IllegalArgumentException.class)
    public void whenThrowException_thenOk() {
        User user = null;
        User result = Optional.ofNullable(user)
                .orElseThrow(() -> new IllegalArgumentException());
    }

}
